package com.hmall.order.Interceptor;

import com.hmall.common.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.Instant;

@Component
public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String ip = request.getRemoteAddr();
        Instant startTime = Instant.now();
        request.setAttribute("logrequestStartTime", startTime);
        String header = request.getHeader("authorization");
        Long value = Long.valueOf(header);
        ThreadLocalUtil.set(value);
//        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取用户token
     //   Method method = handlerMethod.getMethod();
        System.err.println("用户:" + ip +"本次请求，请求头为:"+header);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.remove();
    }
}
